const { readFile, writeFile } = require('fs/promises')

const REPORT_PATH = '../run/result/report.txt'
const TARGET_FILE_PATH = '../entry/src/main/ets/tests/Suites.ets'

function parseReport(reportContent) {
  const suitesMap = {}
  let currentSuite = null
  const lines = reportContent.split('\n')
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim()
    if (line.startsWith('SUITE:')) {
      const suiteMatch = line.match(/\[.*?\]\s+(.+)/)
      if (suiteMatch) {
        currentSuite = suiteMatch[1].trim()
        suitesMap[currentSuite] = []
      }
    } else if (currentSuite && line) {
      const statusMatch = line.match(/^(\w+)\s+(PASS)/)
      if (statusMatch) {
        suitesMap[currentSuite].push(statusMatch[1])
      }
    }
  }
  return suitesMap
}

async function addDisabledTests() {
  try {
    const reportContent = await readFile(REPORT_PATH, 'utf8')
    let content = await readFile(TARGET_FILE_PATH, 'utf8')
    content = content.replace(/\s*\]\s*,\s*\r?\n\s*disabledTests\s*:\s*\[/g, '') // All tests enable.
    const suitesMap = parseReport(reportContent)
    let totalDisabledTests = 0
    for (const [suiteName, passedTests] of Object.entries(suitesMap)) {
      const suiteLine = `name: '${suiteName}'`
      const suiteStart = content.indexOf(suiteLine) + suiteLine.length
      if (suiteStart > 0) {
        const testBlockStart = content.indexOf('tests: [', suiteStart) + 8
        const testBlockEnd = content.indexOf('        ]', testBlockStart)
        if (testBlockStart < testBlockEnd) {
          let disabledTestLines = content.slice(testBlockStart, testBlockEnd).split('\n').filter(it => it)
          let testLines = []
          for (const passed of passedTests) {
            let passedFound = false
            for (const [i, test] of disabledTestLines.entries()) {
              if (test.includes(passed)) {
                passedFound = true
                testLines.push(test)
                disabledTestLines.splice(i, 1)
                break
              }
            }
            if (!passedFound) {
              console.warn(`Test ${passed} is lost`)
            }
          }
          testLines = testLines.sort()
          disabledTestLines = disabledTestLines.sort()
          if (disabledTestLines.length > 0) {
            testLines.push('        ],')
            disabledTestLines.unshift('        disabledTests: [')
          }
          content = [
            content.slice(0, testBlockStart),
            ...testLines,
            ...disabledTestLines,
            content.slice(testBlockEnd)
          ].join('\n')
          totalDisabledTests += disabledTestLines.length
        } else {
        console.warn(`ERROR! Suite ${suiteName} has not been processed!`)
          }
      } else {
        console.warn(`ERROR! Suite ${suiteName} has not been processed!`)
      }
    }
    await writeFile(TARGET_FILE_PATH, content, 'utf8')
    console.info('File updated successfully.')
    console.info(`Total tests disabled: ${totalDisabledTests}`)
  } catch (err) {
    console.error('Error processing files:', err)
  }
}

addDisabledTests()